<?php
declare (strict_types=1);

namespace app\listener\order;

use app\service\core\card\CoreGoodsSaleNumService;
use app\service\core\card\CoreGoodsStockService;
use app\dict\order\OrderDict;
use app\api\model\order\OrderGoods;
use app\service\core\order\CoreOrderLogService;
use think\facade\Log;

class AfterShopOrderFinish
{

    public function handle($data)
    {
        Log::write('订单AfterShopOrderFinish' . json_encode($data));
        try {
            $order_data = $data['order_data'];
            $order_goods_data = $order_data['order_goods'] ?? [];
            //日志
            $main_type = $data['main_type'];
            $main_id = $data['main_id'];
            (new CoreOrderLogService())->add([
                'order_id' => $order_data['order_id'],
                'status' => OrderDict::FINISH,
                'main_type' => $main_type,
                'main_id' => $main_id,
                'type' => OrderDict::ORDER_FINISH_ACTION,
                'content' => ''
            ]);

            //商品累计库存
            //规格累加库存
            $core_goods_stock_service = new CoreGoodsStockService();
            foreach ($order_goods_data as $v) {
                $core_goods_stock_service->inc([
                    'num' => $v['num'],
                    'goods_id' => $v['goods_id'],
                    'sku_id' => $v['sku_id']
                ]);
            }


            //累增收购量
            $core_goods_sale_num_service = new CoreGoodsSaleNumService();
            foreach ($order_goods_data as $v) {
                //商品累计销量
                $core_goods_sale_num_service->inc([
                    'num' => $v['num'],
                    'goods_id' => $v['goods_id'],
                    'sku_id' => $v['sku_id']
                ]);
            }
            //消息发送


            //定时关闭订单允许退款开关
            (new OrderGoods())->where([['order_id', '=', $order_data['order_id']]])->update([
                'is_enable_refund' => 0
            ]);

        } catch ( \Exception $e ) {
            Log::write('订单AfterShopOrderFinish失败' . $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }
}
